package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.IEmployeeService;
import jdk.nashorn.internal.ir.RuntimeNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {


    @Autowired
    private IEmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpSession httpSession, @RequestBody Employee employee) {

        //判断是否为空
        if (employee == null
                || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("账号或密码不能为空!");
        }
        log.info("账号不为空");

        //给密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //数据库校验:select * from tb_employee where username =#{userName}
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);

        //判断emp
        if (emp == null) {
            return R.error("账号不存在!");
        }
        log.info("账号存在");

        //判断密码
        if (!password.equals(emp.getPassword())) {
            return R.error("密码错误!");
        }
        log.info("密码正确");

        //判断账号状态
        if (emp.getStatus() == null) {
            return R.error("账号已被禁用!");
        }
        log.info("账号正常");

        //登录成功
        httpSession.setAttribute("employee", emp);
        log.info("登录成功");
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R logout(HttpSession httpSession) {
        httpSession.removeAttribute("employee");
        return R.success(null);
    }

    @PostMapping
    public R save(@RequestBody Employee employee, HttpSession httpSession) {
        log.info("新增employee");
        //1.确定哪些需要修改
        //password->加密,密码默认为123456
        String password = "123456";
        //密码去除空格
        String replace = password.replace("", " ");
        byte[] bytes = replace.getBytes();
        String s = DigestUtils.md5DigestAsHex(bytes);
        employee.setPassword(s);

        //status默认1,不需要处理

        //createTime:系统时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //createUser/updateUser:从session获取
//        Employee user = (Employee) httpSession.getAttribute("userLogin");
//        employee.setName(user.getName());
//        employee.setCreateUser(user.getId());
//        employee.setUpdateUser(user.getId());

        boolean save = employeeService.save(employee);

        if (save) {

            return R.success(employee);
        }


        return R.error(null);
    }


    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        log.info("分页查询");
        //构建条件
        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery(Employee.class)

                //添加过滤条件
                .like(StringUtils.isNotEmpty(name), Employee::getName, name)

                //排序
                .orderByDesc(Employee::getUpdateTime);

        //构造分页查询
        IPage<Employee> pageInfo = new Page<>(page, pageSize);

        //执行查询
        employeeService.page(pageInfo, lqw);

        return R.success(pageInfo);
    }


    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查信息");
        Employee emp = employeeService.getById(id);
        if (emp == null) {
            return R.error("没查询到对应");
        }
        return R.success(emp);
    }


    @PutMapping
    public R update(@RequestBody Employee employee, HttpSession session) {
        log.info(employee.toString());

        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());

        Employee userLogin = (Employee) session.getAttribute("employee");

        employee.setUpdateUser(userLogin.getId());
        employee.setCreateUser(userLogin.getId());

        employeeService.updateById(employee);

        return R.success("员工信息修改成功");

    }


}